package main

import (
    "database/sql"
    "fmt"
    "go.uber.org/zap"
    "google.golang.org/protobuf/proto"
    "laxkits/lib/laxmysql"
    "laxkits/lib/laxutils"
    KKSG "laxkits/lib/ropb"
)

func TryDelete(conn *laxmysql.LaxMySQLConn) {
    if conn == nil {
        return
    }
    var err error
    var role RoleItemReadNode
    role.Init()
    for i := 0; i < 5; i++ {
        zap.S().Infof("conn:%s, 开始查询role%d", conn.GetId(), i)
        qsql := fmt.Sprintf("select serverid,id,name,account, ItemDataList_0, ItemDataList_1,ItemDataList_2,ItemDataList_3,ItemDataList_4 from player%d.role", i)
        if err = conn.LaxQuery(qsql, func(row *sql.Rows) error {
            if err = row.Scan(role.rowFields...); err != nil {
                zap.S().Warn("查询失败,", err)
                return err
            }
            role.Parse()
            for j := 0; j < 5; j++ {
                var pb KKSG.ItemDataList_0
                if err = proto.Unmarshal(role.GetItemData(j), &pb); err != nil {
                    zap.S().Warn("序列化成pb失败:", err)
                    return err
                }
                if pb.ItemDataList == nil || pb.ItemDataList.ItemDataList == nil {
                    return nil
                }
                needModify := false
                var newPb []*KKSG.Ro_Item
                for _, item := range pb.ItemDataList.ItemDataList {
                    if _, ok := laxutils.ROGlobalConfigNode.ItemIdMap[item.ItemId]; ok {
                        zap.S().Infof("%s 需要删除道具:%d uid:%d 绑定:%d, player:%d, itemidx:%d", role.String(), item.ItemId, item.Uid, item.StateSign, i, j)
                        needModify = true
                    } else {
                        newPb = append(newPb, item)
                    }
                }
                if needModify {
                    pb.ItemDataList.ItemDataList = newPb
                    var dataList []byte
                    if dataList, err = proto.Marshal(&pb); err != nil {
                        zap.S().Warnf("写入数据失败: 修改后pb序列化失败:%v", err)
                        return err
                    }
                    msql := fmt.Sprintf("update player%d.role set ItemDataList_%d = ? where id = ?", i, j)
                    var affect int64
                    if affect, err = conn.LaxExecute(msql, dataList, role.Id); err != nil {
                        zap.S().Warn("执行删除的sql出错:", err)
                        return err
                    }
                    zap.S().Infof("%s 列:%d,删除成功,影响行:%d", role.String(), j, affect)
                }
            }
            return nil
        }); err != nil {
            zap.S().Info("总执行出错:", err)
            return
        }
    }
}
